<!--
 * @Description: 文书列表
 * @Author: E-CHOOSEUS R&D
 * @Date: 2021-12-14 17:40:00
 * @LastEditors: Please set LastEditors
-->
<template>
  <div style="height: calc(100vh - 184px); overflow: auto">
    <div>
      <el-button
        v-has="'nursingDoc:config'"
        class="my-btn"
        type="primary"
        @click="handleConfigOpen"
      >
        文书配置
      </el-button>
      <el-button
        v-has="'nursingDoc:other'"
        class="my-btn mr-15"
        type="success"
        @click="handleViewOther"
      >
        其他表单查看
      </el-button>
      <el-button
        class="my-btn mr-15"
        type="success"
        @click="handleViewOther360p"
      >
        360患者视图
      </el-button>
      <el-input
        v-model="searchName"
        class="w-400"
        placeholder="输入表单名称模糊搜索"
        clearable
      />
    </div>
    <ul class="table">
      <li
        v-for="(item, idx) in docList"
        :key="idx"
        :class="[item.type === activeObj.type ? 'active' : '']"
        @click="handleDoc(item)"
      >
        <span>{{ item.title }}</span>
      </li>
    </ul>
    <!-- 打印功能按钮 -->
    <div class="doc">
      <div
        v-if="activeObj.components === 'TableList'"
        v-loading="isShowRightLoading"
        class="act-bar"
      >
        <img
          class="refresh left mr-10"
          src="@/assets/images/refresh.png"
          @click="toUpdate"
        />
        <CAFileCancel
          :documentCode="activeObj.type"
          moduleCode="nursingDocument"
        />
        <el-button
          v-show="tableData.length > 0"
          v-has="'nursingDoc:export'"
          type="primary"
          @click="handleOutput('dzbl')"
          >电子病历归档</el-button
        >
        <el-button
          v-show="tableData.length > 0"
          v-has="'nursingDoc:export'"
          type="primary"
          @click="handleOutput('sign-without')"
          >CA认证</el-button
        >
        <el-button
          v-show="
            (!isHistory ||
              roles.includes('yx_icu_nurse') ||
              roles.includes('SUPER_ADMIN')) &&
            !isFlow
          "
          v-has="'nursingDoc:edit'"
          class="my-btn"
          type="success"
          @click="toEditEval('', 'add')"
        >
          新 增
        </el-button>
        <el-button
          v-has="'nursingDoc:edit'"
          class="my-btn"
          type="primary"
          @click="saveTableList"
        >
          保 存
        </el-button>
        <el-button
          v-show="activeObj.type == 53"
          v-has="'nursingDoc:edit'"
          class="my-btn"
          type="primary"
          @click="importData"
        >
          导入数据
        </el-button>
        <el-button
          v-show="tableData.length > 0"
          v-has="'nursingDoc:export'"
          v-rights="'DocList:preview'"
          class="my-btn"
          :disabled="selColumn.length == 0"
          @click="handleOutput()"
        >
          导 出
        </el-button>
        <el-button
          v-show="tableData.length > 0"
          v-has="'nursingDoc:export'"
          v-rights="'DocList:preview'"
          class="my-btn"
          @click="handleOutput('print')"
        >
          打印
        </el-button>
      </div>
      <div v-if="activeObj.components === 'TableList'" class="tableList">
        <el-table
          ref="table"
          class="my-table"
          :data="tableData"
          stripe
          :cellStyle="{
            userSelect: 'none'
          }"
          @selection-change="handleSelColumn"
          @row-dblclick="handleSelRow"
        >
          <el-table-column v-if="selection" type="selection" width="50" />
          <el-table-column
            :resizable="false"
            align="center"
            prop="createTime"
            label="评估时间"
          >
            <template slot="header" slot-scope="scope">
              <span>{{ scope.column.label }}</span>
            </template>
            <template slot-scope="scope">
              <!-- {{ formatTime(scope.row.createTime, 'yyyy-MM-dd HH:mm') }} -->
              <el-date-picker
                v-model="scope.row.recordTime"
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                value-format="timestamp"
                placeholder=""
                :clearable="false"
                :disabled="editId !== scope.row.id"
                @change="evaluateTimeChange"
              >
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column
            :resizable="false"
            align="center"
            width="90"
            label="操作"
          >
            <template slot-scope="scope">
              <div
                slot="reference"
                v-has="'nursingDoc:edit'"
                class="img"
                :disabled="!permissionCheck(scope.row) || isFlow"
                @click="toEditEval(scope.row.id, 'edit')"
              >
                <img src="@/assets/images/edit.png" />
              </div>
              <el-popconfirm
                v-has="'nursingDoc:del'"
                title="确认删除该条记录?"
                :disabled="isFlow"
                @confirm="toDelete(scope.row.id)"
              >
                <div
                  slot="reference"
                  class="img"
                  :disabled="!permissionCheck(scope.row)"
                >
                  <img src="@/assets/images/pipe_delete.png" />
                </div>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <Dialog ref="printDialog" :data="activeObj" @refresh="toUpdate" />
        <div v-if="isFormVisible" class="doc-page">
          <Form
            ref="docForm"
            class="docForm"
            :data="activeObj"
            :other-data="otherFormData"
            @refresh="toUpdate"
          />
        </div>
      </div>
      <component
        :is="activeObj.components"
        v-else
        :is-history="isHistory"
        :data="activeObj"
      />
      <el-dialog
        title="文书配置"
        center
        :visible.sync="docConfigVisible"
        width="800px"
      >
        <div class="configList">
          <div v-for="(item, index) in tableList" :key="index" class="item">
            <el-checkbox
              v-model="docConfigList[index]"
              :disabled="item.disabled"
            >
              {{ item.title }}
            </el-checkbox>
          </div>
        </div>
        <span slot="footer">
          <el-button
            class="my-btn big"
            type="info"
            @click="docConfigVisible = false"
            >取 消</el-button
          >
          <el-button
            class="my-btn big"
            type="primary"
            @click="handleConfigConfirm"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { endOfDay, startOfDay } from 'date-fns'
import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  toRefs,
  watch
} from 'vue'
import { useRoute } from 'vue-router/composables'

import { Doc } from '@/api/doc/index'
import { getLastNotVTENew } from '@/api/nursing/evalutation'
import { getTodaySkin } from '@/api/nursing/nursingRecord'
import CAFileCancel from '@/components/CAFileCancel/index.vue'
import { useSign } from '@/hooks'
import { formatTime } from '@/utils/format'
import {
  getBusFromInstance,
  getElementFnFromInstance,
  getStoreFromInstance
} from '@/utils/instance'
import request from '@/utils/request'

import BloodSupplyObserve from './components/BloodSupplyObserve/index.vue'
import Dialog from './components/Dialog.vue'
import FamilyNotice from './components/FamilyNotice/index.vue'
import Form from './components/Form.vue'
import HospitalizationNotice from './components/HospitalizationNotice/index.vue'
import IntensiveCare from './components/IntensiveCare/index.vue'
import IntensiveCare2 from './components/IntensiveCare2/index.vue'
import ObligationsAndRights from './components/ObligationsAndRights/index.vue'
import PICCCatheterRemoval from './components/PICCCatheterRemoval/index.vue'
import PressureUlcerRiskNotice from './components/PressureUlcerRiskNotice/index.vue'
import PreventAspiration from './components/PreventAspiration/index.vue'
import SafeNotice from './components/SafeNotice/index.vue'
import TemperatureChart from './components/TemperatureChart/index.vue'
import { docConfs } from './docConfs.js'

export default defineComponent({
  name: 'DocList',
  components: {
    Dialog,
    TemperatureChart,
    IntensiveCare,
    IntensiveCare2,
    Form,
    PICCCatheterRemoval,
    // 普济表单
    BloodSupplyObserve,
    ObligationsAndRights,
    PressureUlcerRiskNotice,
    PreventAspiration,
    HospitalizationNotice,
    FamilyNotice,
    SafeNotice,
    CAFileCancel
  },
  setup() {
    const state = reactive({
      docConfigVisible: false,
      docConfigList: [],
      showCodes: [],
      activeObj: {},
      searchName: '', // 搜索的表单名称
      tableList: docConfs,
      otherFormData: {}, // 其他表单最新一条数据 用于导入
      tableData: [],
      isShowRightLoading: false, //是否显示loading
      selection: true, // 是否显示多选
      selColumn: [], // 选中的数据
      isFormVisible: false, // 是否显示Form
      table: undefined,
      printDialog: undefined,
      docForm: undefined,
      recordTime: null,
      editId: ''
    })

    const route = useRoute()
    const store = getStoreFromInstance()
    const { $message } = getElementFnFromInstance()
    const bus = getBusFromInstance()
    const { queryUserSignByName } = useSign()

    const patCur = computed(() => store.getters.patCur)

    const isHistory = computed(() => store.getters.isHistory)
    const isFlow = computed(() => store.getters.isFlow)

    const user = computed(() => store.getters.user)

    const roles = computed(() => store.getters.roles)

    const showDocList = computed(() => {
      return state.tableList.filter(v =>
        state.showCodes.some(v2 => v2 == v.type)
      )
    })

    // 搜索后的表单列表
    const docList = computed(() => {
      return showDocList.value.filter(res => {
        return state.searchName ? res.title.includes(state.searchName) : true
      })
    })

    function handleDoc(item) {
      if (state.activeObj.type === item.type) {
        return
      }
      window.localStorage.setItem('last_doc_obj', JSON.stringify(item))
      state.activeObj = item
      if (state.activeObj.components == 'TableList') {
        // 左侧表格右侧Form布局的文书显示Form
        state.isFormVisible = false
        getEvalutions(true)
      }
    }

    function showAddDialog(id = '') {
      if (state.printDialog) {
        state.printDialog.initEditData(id, 'add')
      } else {
        setTimeout(() => {
          showAddDialog((id = ''))
        }, 200)
      }
    }

    function showForm(id = '') {
      state.isFormVisible = true

      nextTick(() => {
        if (state.docForm) {
          // if (state.activeObj.type == 33) {
          //   state.docForm.initEditData(
          //     state.tableData?.length > 0 ? state.tableData[0].id : '',
          //     'add'
          //   )
          // } else {
          state.docForm.initEditData(id, 'add')
          // }
        }
      })
    }

    function getEvalutions(isOpenAddDialog) {
      if (!patCur.value) {
        return
      }
      const data = {
        type: state.activeObj.type,
        patientIdent: patCur.value.patientIdent,
        startTime: patCur.value.startRkTime,
        endTime: patCur.value.endCkTime
      }
      state.isShowRightLoading = true
      Doc.getList(data).then(res => {
        state.tableData = res.data || []
        nextTick(() => {
          if (state.table) {
            state.table.toggleAllSelection()
          }
        })
        state.isShowRightLoading = false
        showForm()
        // if (isOpenAddDialog) {
        //   this.showAddDialog(res.data.length > 0 ? res.data[0].id : '')
        // }
      })
    }

    function toEditEval(id = '', type) {
      // if (state.activeObj.type == 33 && type === 'add') {
      //   state.docForm.initEditData(
      //     state.tableData?.length > 0 ? state.tableData[0].id : '',
      //     type
      //   )
      // } else {
      // this.$refs.printDialog.initEditData(id, type)
      state.editId = id
      state.recordTime = null
      state.docForm.initEditData(id, type)
      // }
    }

    function evaluateTimeChange(params) {
      state.recordTime = params
    }

    // 列表表单保存事件
    function saveTableList() {
      bus.$emit('recordTime', state.recordTime)
      state.docForm.save()
      state.editId = ''
    }

    function toUpdate() {
      getEvalutions()
    }

    function toDelete(id) {
      Doc.del({ id }).then(() => {
        $message.success('删除成功!')
        toUpdate()
        getEvalutions()
      })
    }

    function toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          state.table.toggleRowSelection(row)
        })
      } else {
        state.table.clearSelection()
      }
    }

    function handleSelColumn(selections) {
      state.selColumn = selections
    }

    function handleSelRow(row) {
      state.docForm.initEditData(row.id, 'view')
    }

    function handleCancelSel() {
      state.table.clearSelection()
      // this.selection = false;
    }

    async function handleOutput(type = 'output') {
      const signs = state.selColumn?.map(v => {
        const jsonText = v.jsonText ? JSON.parse(v.jsonText) : {}
        return jsonText.sign
      })
      await queryUserSignByName(signs, 'nursingDocument', state.activeObj.type)
      state.printDialog.setOperateType(type)
      state.printDialog.initPreviewData(state.selColumn)
    }

    function permissionCheck(row) {
      if (
        roles.value &&
        (roles.value.includes('SUPER_ADMIN') ||
          roles.value.includes(window.nurseLeaderRole))
      ) {
        return true
      }
      if (row.createdBy === user.value.id) {
        return true
      }
      return false
    }

    function handleConfigOpen() {
      getConfigList()
      state.docConfigVisible = true
    }

    function getConfigList() {
      const params = {
        hospitalNumber: patCur.value.hospitalNumber,
        patientIdent: patCur.value.patientIdent,
        category: 1
      }
      Doc.getDocConfig(params).then(({ data }) => {
        state.showCodes = data?.map(v => v.code) || []
        if (!state.showCodes.includes(String(state.activeObj.type))) {
          state.activeObj = {}
          window.localStorage.setItem('last_doc_obj', JSON.stringify({}))
        }
        getFilterTableData()
      })
    }

    function getFilterTableData() {
      if (!patCur.value) {
        return
      }
      const para = {
        patientIdent: patCur.value.patientIdent,
        startTime: patCur.value.startRkTime,
        endTime: patCur.value.endCkTime
      }
      Doc.getList(para).then(({ data }) => {
        data = data.map(res => String(res.type))
        state.tableList.forEach(res => {
          if (data.includes(String(res.type))) {
            state.showCodes = [...new Set([...state.showCodes, ...data])]
            res.disabled = true
          } else {
            res.disabled = false
          }
        })
        const docConfigList = state.tableList.map(v =>
          state.showCodes.some(v2 => v2 == v.type)
        )
        state.docConfigList = docConfigList
      })
    }

    function handleConfigConfirm() {
      const codes = []
      state.docConfigList.forEach((v, index) => {
        if (v) {
          codes.push(state.tableList[index].type)
        }
      })
      const params = {
        hospitalNumber: patCur.value.hospitalNumber,
        patientIdent: patCur.value.patientIdent,
        category: 1,
        codes
      }
      Doc.saveDocConfig(params).then(() => {
        state.showCodes = codes
        $message.success('保存成功!')
        state.docConfigVisible = false
      })
    }

    function handleViewOther() {
      // window.open(window.emrInpatUrl + patCur.value.hospitalNumber)
      window.open(
        'https://100.200.2.10:1443/imedical/web/form.htm?TPSID=DH01&USERNAME=hs01'
      )
    }

    // 360患者视图
    async function handleViewOther360p() {
      const para = {
        clientId: 'HOSP-ICU',
        sign: '',
        timestamp: +new Date(),
        userId: user.value.account,
        // idCardType: '2',
        orgCode: '40079411',
        regId: patCur.value.regId,
        sourceType: '2'
      }

      const axios = {
        url: '/api/patient/view/patient/param',
        method: 'post',
        data: para
      }

      await request(axios).then(res => {
        const { sign, ktoken } = res.data
        const url =
          'http://100.200.0.106:8080/kthdc-360view-ui/#/auth?' +
          `ktoken=${ktoken}` +
          '&client_id=HOSP-ICU' +
          '&timestamp=' +
          para.timestamp +
          '&orgCode=40079411&sourceType=2&regId=' +
          patCur.value.regId +
          '&userId=' +
          user.value.account +
          '&sign=' +
          sign

        window.open(url)
      })
    }

    // 导入最新一条记录
    async function importData() {
      const form = {}
      const { data } = await getLastNotVTENew({
        patientIdent: patCur.value.patientIdent,
        hospitalNumber: patCur.value.hospitalNumber,
        pgCode: state.activeObj.pgCode,
        dataSource: '1'
      })
      form['data'] = data
      if (state.activeObj.type == 53) {
        // 压疮要获取今天的压疮记录
        const { data: data2 } = await getTodaySkin({
          patientIdent: patCur.value.patientIdent,
          startTime: startOfDay(new Date()).getTime(),
          endTime: endOfDay(new Date()).getTime()
        })
        form['yc'] = data2
      }
      state.otherFormData = form
    }

    watch(
      patCur,
      (n, o) => {
        if (n) {
          getConfigList()
          if (
            (!o ||
              n.patientIdent != o.patientIdent ||
              (n.patientIdent == o.patientIdent &&
                n.startRkTime != o.startRkTime)) &&
            state.activeObj.components === 'TableList'
          ) {
            getEvalutions()
          }
        }
      },
      { immediate: true }
    )

    onMounted(() => {
      const params = route.params
      const activeObj = state.tableList.find(v =>
        params.activeType ? v.type === Number(params.activeType) : 12
      )
      if (activeObj) {
        handleDoc(activeObj)
      } else {
        const lastDocObjStr = window.localStorage.getItem('last_doc_obj')
        if (lastDocObjStr) {
          try {
            const lastDocObj = JSON.parse(lastDocObjStr)
            if (lastDocObj.type != 12 && lastDocObj.type != 5) {
              state.activeObj = lastDocObj

              if (state.activeObj.components === 'TableList') {
                getEvalutions()
              }
            }
          } catch (err) {}
        }
      }
    })

    return {
      ...toRefs(state),
      user,
      roles,
      isHistory,
      isFlow,
      showDocList,
      docList,
      handleDoc,
      handleOutput,
      handleSelColumn,
      handleSelRow,
      permissionCheck,
      toEditEval,
      toDelete,
      toUpdate,
      toggleSelection,
      handleCancelSel,
      showAddDialog,
      handleConfigOpen,
      handleConfigConfirm,
      handleViewOther,
      handleViewOther360p,
      formatTime,
      saveTableList,
      importData,
      evaluateTimeChange
    }
  }
})
</script>

<style scoped lang="scss">
// @import '@/views/doc/styles/doc-common.scss';

ul,
li {
  list-style: none;
  padding: 0;
  margin: 0;
}

.table {
  margin-top: 10px;
  color: #333;
  display: flex;
  flex-wrap: wrap;

  li {
    margin-bottom: 10px;
    line-height: 32px;
    padding: 0 10px;
    cursor: pointer;
    border-radius: 4px;
    background: #fff;

    &:not(:last-child) {
      margin-right: 10px;
    }

    &.active,
    &:hover {
      color: #fff;
      background: #165dff;
      box-shadow: 0 2px 8px 0 rgb(0 0 0 / 25%);
    }

    .rightIcon {
      cursor: pointer;
      font-size: 18px;
      color: gray;
    }
  }

  .doc {
    margin-bottom: 10px;
    overflow: hidden;
    background: #fff;
    border-radius: 6px;
    height: calc(100vh - 110px);

    .btn {
      padding-right: 30px;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .el-button {
        min-width: 120px;
        min-height: 36px;
        font-size: 14px;
        border-radius: 4px;
      }
    }

    .form {
      display: inline-block;
      text-align: left;
    }

    .doc-container {
      font-family: Tahoma, Arial, SimSun, '宋体', 'Microsoft YaHei', '微软雅黑',
        sans-serif;
      margin: 0 auto;
      width: 210mm;
      height: 297mm;
      background-color: #fff;
      display: flex;
      flex-direction: column;
      align-items: center;
      border: 1px solid #f0f0f0;
    }
  }
}

.doc-page {
  overflow-y: auto;
}

.m {
  &b {
    &-20 {
      margin-bottom: 20px;
    }
  }

  &-20 {
    margin: 20px;
  }
}

.doc {
  margin-bottom: 10px;
  // overflow: hidden;
  background: #fff;
  border-radius: 6px;
  // height: calc(100vh - 110px);
}

.doc-page {
  overflow-y: auto;
}

.tableList {
  display: grid;
  grid-template-columns: 280px auto;
  margin-top: 15px;
  margin-left: 15px;
  height: calc(100% - 80px);
  overflow-y: auto;
}

.h {
  &-100p {
    height: 100%;
  }
}

.mr-10 {
  margin-right: 10px;
}

.act-bar {
  min-height: 52px;
  padding: 9px 10px;
  border-bottom: 1px solid #f2f4f5;
  text-align: right;
  border-radius: 6px 6px 0 0;
  background: #fff;
}

.refresh {
  width: 32px;
  padding: 8px;
  background: #155ef3;
  border-radius: 4px;
  cursor: pointer;
  vertical-align: top;
}

.img {
  width: 34px;
  height: 34px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transform: translateY(1px);
  cursor: pointer;

  img {
    height: 14px;
  }
}

.configList {
  margin: 0 40px;
  max-height: 60vh;
  overflow-y: auto;
  border: 1px solid #f2f4f5;

  .item {
    background: #f9f9f9;
    padding: 4px 30px;

    &:nth-child(even) {
      background: #fff;
    }
  }

  :deep {
    .el-checkbox__input {
      margin-top: 2px;
    }

    .el-checkbox__inner {
      border: 1px solid #c7cbd4;
    }

    .el-checkbox__label {
      padding-left: 30px;
      color: #333;
    }

    .el-checkbox__input.is-checked .el-checkbox__inner {
      background-color: #165dff;
      border-color: #165dff;
    }

    .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
      background-color: #c7cbd4;
      border-color: #c7cbd4;
    }

    .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
      border-color: #fff;
    }

    .el-checkbox__input.is-disabled + span.el-checkbox__label {
      color: #333;
    }
  }

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 3px;
    background: #bfbfbf;
  }

  ::v-deep {
    .el-checkbox {
      display: flex;
      align-items: center;
      white-space: normal;
      padding: 6px 0;
    }
  }
}

:deep {
  .el-dialog--center .el-dialog__body {
    text-align: initial;
    padding: 25px 25px 10px;
  }

  .el-date-editor.el-input {
    width: 100%;
    text-align: center !important;
  }

  .el-date-editor .el-input__inner {
    margin: 0;
    padding: 0;
    width: 100%;
    font-size: 14px;
    color: #000;
    border: none;
    text-align: center !important;
  }

  .el-input__prefix {
    display: none;
  }

  .el-input__suffix {
    right: 0;

    .el-input__icon {
      line-height: 26px;
    }
  }
}

.mr-15 {
  margin-right: 15px;
}
</style>
